import BackGround from './runtime/background';
import GameInfo from './runtime/gameinfo';
import Music from './runtime/music';
import DataBus from './databus';
import CharacterManager from './managers/character-manager';
import RecordManager from './managers/record-manager';
import { SCREEN_WIDTH, SCREEN_HEIGHT } from './render';

// 按钮区域常量
const BTN_WIDTH = 150;
const BTN_HEIGHT = 40;
const RESTART_BTN_X = (SCREEN_WIDTH - BTN_WIDTH) / 2;
const RESTART_BTN_Y = SCREEN_HEIGHT / 2 + 70;
const LEADERBOARD_BTN_X = (SCREEN_WIDTH - BTN_WIDTH) / 2;
const LEADERBOARD_BTN_Y = RESTART_BTN_Y + BTN_HEIGHT + 20;

// 获取canvas对象
const canvas = wx.createCanvas();
const ctx = canvas.getContext('2d');
let databus = new DataBus();

export default class Main {
  constructor() {
    this.aniId = 0;
    this.restart();
  }

  restart() {
    databus.reset();
    this.bg = new BackGround();
    this.characterManager = new CharacterManager(canvas);
    
    // 设置游戏结束回调
    this.characterManager.onGameOver = this.handleGameOver.bind(this);
    
    // 初始化角色（顺序重要）
    this.characterManager.initPlayer();  // 先初始化玩家
    this.characterManager.initAllies();  // 然后初始化队友
    this.characterManager.initEnemys(); // 最后初始化敌人
    
    this.gameinfo = new GameInfo();
    this.music = new Music();
    databus.music = this.music;
    databus.debug = false;
    
    this.bindLoop = this.loop.bind(this);
    this.hasEventBind = false;
    
    // 绑定触摸事件
    if (!this.hasEventBind) {
      this.hasEventBind = true;
      canvas.addEventListener('touchstart', this.touchEventHandler.bind(this));
    }
    
    window.cancelAnimationFrame(this.aniId);
    this.aniId = window.requestAnimationFrame(this.bindLoop, canvas);
  }

  render() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 先渲染背景
    this.bg.render(ctx);
    
    // 使用CharacterManager渲染所有游戏对象
    this.characterManager.render(ctx);
    
    // 最后渲染游戏信息
    this.gameinfo.render(ctx);
  }

  update() {
    if (databus.gameOver) return;
    
    // 使用CharacterManager更新所有游戏对象
    this.characterManager.update();

    // 更新游戏统计数据
    databus.updateStats(0.1); // 每帧增加0.1的距离
    
    // 更新饥饿度和其他状态
    databus.update();
  }

  // 处理游戏结束
  handleGameOver() {
    if (!databus.gameOver) {
      // 使用新的setGameOver方法
      databus.setGameOver();
      
      // 上传分数到云开发
      databus.uploadScore();
      
      // 显示排行榜按钮
      this.gameinfo.showLeaderboard = true;

      // 绑定触摸事件
      if (!this.hasEventBind) {
        this.hasEventBind = true;
        canvas.addEventListener('touchstart', this.touchEventHandler.bind(this));
      }
    }
  }

  loop() {
    databus.frame++;
    this.update();
    this.render();
    this.aniId = window.requestAnimationFrame(this.bindLoop, canvas);
  }

  touchEventHandler(e) {
    e.preventDefault();
    
    // 获取触摸位置并转换为canvas坐标
    const touch = e.touches[0];
    const canvasRect = canvas.getBoundingClientRect();
    const scaleX = canvas.width / canvasRect.width;
    const scaleY = canvas.height / canvasRect.height;
    const x = (touch.clientX - canvasRect.left) * scaleX;
    const y = (touch.clientY - canvasRect.top) * scaleY;
    
    // 游戏结束界面的按钮处理
    if (databus.gameOver) {
      // 重新开始按钮
      if (x >= RESTART_BTN_X && 
          x <= RESTART_BTN_X + BTN_WIDTH && 
          y >= RESTART_BTN_Y && 
          y <= RESTART_BTN_Y + BTN_HEIGHT) {
        this.restart();
        return;
      }
      
      // 排行榜按钮
      if (x >= LEADERBOARD_BTN_X && 
          x <= LEADERBOARD_BTN_X + BTN_WIDTH && 
          y >= LEADERBOARD_BTN_Y && 
          y <= LEADERBOARD_BTN_Y + BTN_HEIGHT) {
        databus.showLeaderboard = true;
        databus.getLeaderboardData();
        return;
      }
    }
    
    // 排行榜界面的返回按钮处理
    if (databus.showLeaderboard) {
      const backBtnX = canvas.width / 2 - 75;
      const backBtnY = canvas.height - 70;
      const backBtnWidth = 150;
      const backBtnHeight = 40;
      
      if (x >= backBtnX && 
          x <= backBtnX + backBtnWidth && 
          y >= backBtnY && 
          y <= backBtnY + backBtnHeight) {
        databus.showLeaderboard = false;
        return;
      }
    }
    
    // 游戏进行中，控制玩家移动
    if (!databus.gameOver && !databus.showLeaderboard && databus.player) {
      databus.player.setMoveTarget(x, y);
    }
  }
}